<template>
<view>
<view class="body ">
<!-- 公告 -->
<!-- <view class='notice'>
  <image src='http://image.tunzai.vip/tunzai/2018_11/29/14/48/14_966.jpg?x-oss-process=style/preview_120' class='noticeIcon'></image>
  <view class='scroll_view_border'>
    <text class='noticeText srcoll_view' wx:if="{{promotionInfo.description}}" title="{{promotionInfo.description}}">{{promotionInfo.description}}</text>
    <text class='noticeText' wx:else>暂无公告</text>
  </view>
</view> -->
<!-- 品牌详情 -->
  <view class="promotionBanrdInfo" v-if="promotionInfo.mainBrandBean.brandIcon">
    <image class="promotionBanrdLogo" :src="promotionInfo.mainBrandBean.brandIcon + '?x-oss-process=style/preview'"></image>
    <text class="promotionBanrdName">{{promotionInfo.mainBrandBean.brandName}}</text>
    <text class="promotionBanrdDescribe">{{promotionInfo.mainBrandBean.brandDescription}}</text>
  </view>
  <view class="promotionBanrdInfo" v-else>
    <image class="promotionBanrdLogo" :src="setting.logo + '?x-oss-process=style/preview'"></image>
    <text class="promotionBanrdName">{{promotionInfo.name}}</text>
    <text class="promotionBanrdDescribe">{{promotionInfo.description}}</text>
  </view>
  <!-- 倒计时 -->
  <view class="promotionCountDown" :style="'background:linear-gradient(135deg,' + setting.secondColor + ' 0%,' + setting.defaultColor + ' 100%);'">
    <block v-if="promotionState">
      <text class="promotionName">{{promotionInfo.name}}</text>
      <view class="promotionTimer">
        <time :receiveData="promotionInfo.promotionEndDate" v-if="promotionInfo.promotionEndDate"></time>
        <text class="timeText">后结束</text>
      </view>
    </block>
    <block v-else>
      <view class="promotionTimer">
        <time :receiveData="promotionInfo.promotionStartDate" v-if="promotionInfo.promotionStartDate"></time>
        <text class="timeText">后开始</text>
      </view>
      <!-- <text class='setReminders' style='color:{{setting.defaultColor}}'>设置提醒</text> -->
    </block>
  </view>
  <!-- 产品列表start -->
  <view class="productList" v-if="promotionState">
    <view class="productItem" v-for="(item, index) in productData" :key="index" @tap="toProductDetail" :data-id="item.id">
      <!-- <view class='shareBtn' catchtap='shareBtn' data-id='{{item.id}}' data-type='product'>
        <image class='shareBtnImg' src='http://image.tunzai.vip/tunzai/2018_10/24/13/58/50_462.jpg?x-oss-process=style/preview_120'></image>
      </view> -->
      <!-- 分享的两种 -->
        <!-- <view class='sharaContent' wx:if="{{showIndex==item.id}}">
          <button class='sharaLink' open-type='share' data-item='{{item}}' data-type='product' catchtap='shareProductPages'>
            <image class='sharaLinkIcon' src='http://image1.sansancloud.com/sansancloud/2018_9/10/10/16/1_467.jpg?x-oss-process=style/preview_120'></image>
            <text style='font-size:24rpx'>分享</text>
          </button>
          <button class='sharaPoster' data-id='{{item.id}}' data-type='product' catchtap='shareProductPoster'>
            <image class='sharaPosterIcon' src='http://image1.sansancloud.com/sansancloud/2018_9/10/10/4/26_910.jpg?x-oss-process=style/preview_120'></image>
            <text style='font-size:24rpx'>海报</text>
          </button>
        </view> -->
      <!-- 分享的两种 -->
      <view class="productImg">
        <image :src="item.imagePath + '?x-oss-process=style/preview'" mode="aspectFit" class="productImgUrl"></image>
        <view class="outPrint" v-if="item.stock<=0">
             <view class="outPrintBg"></view>
             <view class="outPrintText"><text>已抢光</text></view>
        </view>
      </view>
      <view class="productPriceAndStock">
        <view style="height:56rpx;">
          <component-price-group :receiveData="item"></component-price-group>
          <!-- <text class='productPrice' style='color:{{setting.defaultColor}}'>¥{{item.price}}</text>
          <text class='productTagPrice'>¥{{item.tagPrice}}</text> -->
        </view>
        <!-- <view class='productStock'>
          <text class='usedProductStockPercent' style='position:absolute;left:{{item.stockPercent/100*100+10}}rpx;' wx:if="{{item.stockPercent<22}}">{{item.stockPercent}}%</text>
          <view class='usedProductStock' style='background:{{setting.defaultColor}};width:{{item.stockPercent}}%'>
            <text class='usedProductStockPercent' wx:if="{{item.stockPercent>22}}">{{item.stockPercent}}%</text>
          </view>
        </view> -->
      </view>
      <view class="productName">
        <text class="limitText">{{item.name}}</text>
      </view>
    </view>
  </view>
  <!--产品列表end  -->
  <!-- 未开始的活动展示start -->
  <!-- 富文本 -->
  <view class>
    <!-- <component is="init" :wxParseData="article.nodes"></component> -->
  </view>
  <!-- 未开始的活动展示end -->
</view>
<!-- 产品海报 -->
<!-- <posters :proId="productId" :shopId="shopId" :ewmImgUrl="qrCodeUrl" v-if="posterState" @closePoaster="getChilrenPoster"></posters> -->
</view>
</template>

<script>
export default {
  data() {
    return {
      promotionInfo: {},
      posterState: false,
      productId: 0,
      shopId: 0,
      promotionState: false,
      showIndex: 0,
      params: {
        belongShop: "",
        page: 1,
        productName: "",
        startPrice: "",
        endPrice: "",
        promotionId: ""
      },
      qrCodeUrl: "",
      reqState: false,
      productData: "",
      id: "",
      setting: "",
      article_article: ""
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("hahahahahahah这是id", options);
    this.setData({
      id: options.promotionId,
      setting: getApp().globalData.setting.platformSetting,
      shopId: getApp().globalData.setting.platformSetting.defaultShopBean.id
    });
    console.log("setting", this.setting);
    this.getProductData(this.params);
    this.getPromotionInfo(this.params);
  },
  onReady: function () {},
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  // 分享
  onShareAppMessage: function (res) {
    console.log('onShareAppMessage=====', res);

    if (res.from == "button") {
      console.log(res); // 商品id

      let id = res.target.dataset.item.id;
      let focusData = res.target.dataset.item;

      if (!focusData.brandName || focusData.brandName == "") {
        focusData.brandName = "";
      }

      ;
      let imageUrl = focusData.imagePath;
      let shareName = '活动价：￥' + focusData.price + '(原价：￥' + focusData.tagPrice + ')' + focusData.brandName + focusData.name;
      let shareParams = {};
      shareParams.productName = focusData.name;
      console.log('nnnnnnnnnn' + shareName);
      shareParams.id = id;
      console.log("shareParams", shareParams);
      return getApp().globalData.shareForFx2('promotion_products', shareName, shareParams, imageUrl);
    } else {
      let that = this;
      let promotionInfo = that.promotionInfo;
      console.log('promotionInfo:', promotionInfo);
      let title = promotionInfo.name;
      let id = promotionInfo.id;
      let banner = promotionInfo.promotionBanner;
      let params = {};
      params.promotionId = id;
      params.title = title;
      params.SHARE_PROMOTION_PRODUCTS_PAGE = id;
      console.log('params:' + JSON.stringify(params));
      return getApp().globalData.shareForFx2('promotion_products', '', params, banner);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('onPullDownRefresh');
    let that = this;
    that.params.page = 1;
    that.getProductData(that.params);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('onReachBottom');
    var that = this;

    if (that.params.totalSize > that.params.page * that.params.pageSize) {
      // wx.showLoading({
      //   title:'加载中...'
      // })
      getApp().globalData.showToastLoading('加载中...', true);
      that.params.page++; // 组件内的事件

      that.getProductData(that.params);
    } else {
      wx.showToast({
        title: '到底了',
        icon: 'success',
        duration: 1000
      });
      console.log('到底了', that.params.page);
    }
  },
  methods: {
    shareBtn: function (e) {
      let that = this;
      console.log('====e====', e);
      let index = e.currentTarget.dataset.id;
      that.setData({
        showIndex: index
      });
    },
    // 开启活动海报
    shareProductPoster: function (event) {
      console.log('====shareProductPoster====', event);
      this.setData({
        showIndex: 0
      });
      this.setData({
        posterState: true
      });
      this.setData({
        productId: event.currentTarget.dataset.id
      });
      let data = {
        type: event.currentTarget.dataset.type,
        id: event.currentTarget.dataset.id
      };
      let qrCodeUrl = getApp().globalData.getQrCode(data);
      console.log('qrCodeUrl===', qrCodeUrl);
      this.setData({
        qrCodeUrl: qrCodeUrl
      });
    },
    shareProductPages: function (event) {
      console.log('====shareProductPages====', event);
    },
    getChilrenPoster: function () {
      console.log('colsePoster');
      this.setData({
        posterState: false
      });
    },
    toProductDetail: function (e) {
      console.log(e.currentTarget.dataset.id); // product_detail.html?productId= 9219;

      var a = "product_detail.html?productId=" + e.currentTarget.dataset.id;
      getApp().globalData.linkEvent(a);
    },

    /* 获取数据 */
    getProductData: function (param) {
      let that = this;
      param.promotionId = this.id;
      let customIndex = getApp().globalData.AddClientUrl("/more_product_list.html", param, 'get'); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          that.setData({
            reqState: true
          });
          console.log("特卖数据", res.data);
          that.params.pageSize = res.data.pageSize;
          that.params.totalSize = res.data.totalSize;
          let productList = res.data.result;

          if (!productList) {
            productList = [];
          } // for(let i=0;i<productList.length;i++){
          //   productList[i].stockPercent = Math.floor((productList[i].totalStock - productList[i].stock) / (productList[i].totalStock) * 100)
          // }


          if (that.params.page == 1) {
            that.setData({
              productData: productList
            });
          } else {
            that.setData({
              productData: that.productData.concat(productList)
            });
          }

          console.log('that.data.productData', that.productData);
          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '加载失败，点击【确定】重新加载',
            success: function (res) {
              console.log('', res);

              if (res.confirm) {
                that.getProductData(that.params, 1);
              } else if (res.cancel) {
                getApp().globalData.toIndex();
              }
            }
          });
        }
      });
    },
    getPromotionInfo: function (param) {
      let that = this;
      param.promotionId = this.id;
      let customIndex = getApp().globalData.AddClientUrl("/get_promotions_detail.html", param, 'get'); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("getPromotionInfo", res);
          let promotionInfo = res.data.relateObj;
          let nowData = new Date();
          let promotionState = false;
          let startTime = promotionInfo.startDate;
          startTime = startTime.replace(/\-/g, "/");
          startTime = new Date(startTime);

          if (startTime >= nowData) {
            console.log('活动未开始');
            promotionState = false;
            promotionInfo['promotionStartDate'] = {
              startTime: promotionInfo.startDate,
              background: '#fff',
              color: that.setting.defaultColor,
              fontSize: 26
            };

            if (promotionInfo.content) {
              //WxParse.wxParse('article', 'html', promotionInfo.content, that)
              setTimeout(function () {
                that.article_article = promotionInfo.content;
              });
            }
          } else {
            console.log('活动已开始');
            promotionState = true;
            promotionInfo['promotionEndDate'] = {
              endTime: promotionInfo.endDate,
              background: '#fff',
              color: that.setting.defaultColor,
              fontSize: 26
            };
          }

          that.setData({
            promotionInfo: promotionInfo
          });
          that.setData({
            promotionState: promotionState
          });
          console.log('promotionInfo', that.promotionInfo);
          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>